// pages/delivery/delivery.js
import http from '../../utils/http.js'
const apiConfig = require('../../utils/apiConfig.js')
Page({
  data: {
    formData: {
      now_date: '',
      customer_id: null,
      manufacturer_id: null,
      goods_id: null,
      cost_price: 0,
      sales_price: 0,
      num: 0,
      total_price: 0
    },
    customers: [],
    manufacturers: [],
    products: [],
    currentPageProduct: 1,
    totalPagesProduct: 1,
    isLoadingProduct: false,
    searchQueryProduct: '',
    selectedCustomer: null,
    selectedManufacturer: null,
    selectedProduct: null,
    currentPage: 1,
    totalPages: 1,
    isLoading: false,
    searchQuery: '',
    debounceTimer: null,
    currentPageManufacturer: 1,
    totalPagesManufacturer: 1,
    isLoadingManufacturer: false
  },

  onLoad() {
    this.loadCustomers();
    this.loadManufacturers();
  },

  loadCustomers() {
    if (this.data.isLoading || this.data.currentPage > this.data.totalPages) return;
    this.setData({ isLoading: true });
    console.log('获取客户列表',this.data.currentPage)
    http.request({
      url: apiConfig.getCustomerList,
      data: {
        page: this.data.currentPage,
        per_page: 10,
        customer_name: this.data.searchQuery
      }
      }).then(res=>{
        console.log('获取客户列表',res)
        if (res.status == 200) {
          const newCustomers = res.data.data;
          this.setData({
            customers: this.data.currentPage === 1 ? newCustomers : [...this.data.customers, ...newCustomers],
            totalPages: res.data.last_page
          });
        }
      }).catch(err => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      })
    
  },

  handleSearch(e) {
    const value = e.detail.value.trim();
    if (this.data.debounceTimer) clearTimeout(this.data.debounceTimer);
    this.data.debounceTimer = setTimeout(() => {
      this.setData({
        searchQuery: value,
        currentPage: 1
      }, () => this.loadCustomers());
    }, 500);
  },

  onReachBottom() {
    if (!this.data.isLoading && this.data.currentPage < this.data.totalPages) {
      this.setData({ currentPage: this.data.currentPage + 1 }, () => this.loadCustomers());
    }
    if (!this.data.isLoadingManufacturer && this.data.currentPageManufacturer < this.data.totalPagesManufacturer) {
      this.setData({ currentPageManufacturer: this.data.currentPageManufacturer + 1 }, () => this.loadManufacturers());
    }
    if (!this.data.isLoadingProduct && this.data.currentPageProduct < this.data.totalPagesProduct) {
      this.setData({ currentPageProduct: this.data.currentPageProduct + 1 }, () => this.loadProducts());
    }
  },

  loadManufacturers() {
    if (this.data.isLoadingManufacturer || this.data.currentPageManufacturer > this.data.totalPagesManufacturer) return;
    
    this.setData({ isLoadingManufacturer: true });
    
    http.request({
      url: apiConfig.getManufacturerList,
      data: {
        page: this.data.currentPageManufacturer,
        per_page: 10
      }
    }).then(res => {
      if (res.status == 200) {
        const newManufacturers = res.data.data;
        this.setData({
          manufacturers: this.data.currentPageManufacturer === 1? newManufacturers : [...this.data.manufacturers,...newManufacturers],
          totalPagesManufacturer: res.data.last_page
        });
      }
    })
      complete: () => this.setData({ isLoadingManufacturer: false })
  },

  bindDateChange(e) {
    this.setData({'formData.now_date': e.detail.value});
  },

  bindCustomerChange(e) {
    const index = e.detail.value;
    const customer = this.data.customers[index];
    console.log('选择的客户',customer)
    this.setData({
      selectedCustomer: customer,
      'formData.customer_id': customer.id
    });
  },

  bindManufacturerChange(e) {
    const index = e.detail.value;
    const manufacturer = this.data.manufacturers[index];
    this.setData({
      selectedManufacturer: manufacturer,
      'formData.manufacturer_id': manufacturer.id,
      currentPageProduct: 1,
      searchQueryProduct: ''
    }, () => this.loadProducts());
  },

  bindProductChange(e) {
    const index = e.detail.value;
    const product = this.data.products[index];
    this.setData({
      selectedProduct: product,
      'formData.goods_id': product.id,
      'formData.cost_price': product.cost_price,
      'formData.sales_price': product.sales_price
    });
    this.calculateTotal();
  },

  bindNumInput(e) {
    this.setData({'formData.num': e.detail.value});
    this.calculateTotal();
  },

  calculateTotal() {
    const { sales_price, num } = this.data.formData;
    this.setData({'formData.total_price': (sales_price * num).toFixed(2)});
  },

  formSubmit() {
    console.log('提交数据1',this.data.formData)
    if (!this.validateForm()) return;
    console.log('提交数据2',this.data.formData)
    if (!this.data.isLoading) return;
    console.log('提交数据3',this.data.formData)
    this.setData({ isLoading: true });
    http.request({
      url: apiConfig.addDelivery,
      method: 'POST',
      data: {
        customer_id: parseInt(this.data.formData.customer_id),
        goods_id: parseInt(this.data.formData.goods_id),
        manufacturer_id: parseInt(this.data.formData.manufacturer_id),
        cost_price: parseFloat(this.data.formData.cost_price),
        sales_price: parseFloat(this.data.formData.sales_price),
        num: parseInt(this.data.formData.num),
        now_date: this.data.formData.now_date,
        total_price: parseFloat(this.data.formData.total_price)
      }
    }).then(res => {
      console.log('提交数据',res)
      if (res.status == 200) {
        wx.showToast({ title: '提交成功' });
        this.setData({
          formData: {
            now_date: '',
            customer_id: null,
            manufacturer_id: null,
            goods_id: null,
            cost_price: 0,
            sales_price: 0,
            num: 0,
            total_price: 0
          }
        }, () => {
          wx.navigateBack();
        });
      } else {
        wx.showToast({ title: '提交失败', icon: 'none' });
      }
    })
      .catch(err => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      })
     
      complete: () => this.setData({ isLoading: false })
  },

  validateForm() {
    const requiredFields = ['now_date', 'customer_id', 'manufacturer_id', 'goods_id'];
    return requiredFields.every(field => !!this.data.formData[field]);
  },

  loadProducts() {
    if (this.data.isLoadingProduct || this.data.currentPageProduct > this.data.totalPagesProduct) return;
    
    this.setData({ isLoadingProduct: true });
    
    http.request({
      url: apiConfig.getGoodsList,
      data: {
        page: this.data.currentPageProduct,
        per_page: 10,
        goods_name: this.data.searchQueryProduct,
        manufacturer_id: this.data.formData.manufacturer_id
      }
    }).then(res => {
      console.log('获取商品列表',res)
      if (res.status == 200) {
        const newProducts = res.data.data;
        this.setData({
          products: this.data.currentPageProduct === 1 
            ? newProducts 
            : [...this.data.products, ...newProducts],
          totalPagesProduct: res.data.last_page
        });
      }
    })
    complete: () => this.setData({ isLoadingProduct: false })
  },

  handleSearchProduct(e) {
    const value = e.detail.value.trim();
    if (this.data.debounceTimer) clearTimeout(this.data.debounceTimer);
    this.data.debounceTimer = setTimeout(() => {
      this.setData({
        searchQueryProduct: value,
        currentPageProduct: 1
      }, () => this.loadProducts());
    }, 500);
  }
})